import 'package:flutter/material.dart';

import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';

class SortCondition {
  String? name;
  String? value;
  bool? isSelected;

  SortCondition({this.name, this.isSelected, this.value});
}

class TopFilter extends StatefulWidget {
  TopFilter(
      {super.key,
      required this.options,
      this.defaultSelectionIdx,
      this.showAll,
      this.itemTap,
      required this.stackKey,
      required this.content});
  List<dynamic> options = []; //筛选项目
  Function? itemTap;
  GlobalKey stackKey;
  Widget content;
  int? defaultSelectionIdx = 0;

  bool? showAll = false; //是否显示“全部”

  @override
  State<TopFilter> createState() => _TopFilterState();
}

class _TopFilterState extends State<TopFilter>
    with AutomaticKeepAliveClientMixin {
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  String _dropDownHeaderItemStrings = '';

  bool fiterOpened = false; //筛选面板展开

  List<SortCondition> _brandSortConditions = [];

  dynamic _selectBrandSortCondition;

  @override
  void initState() {
    super.initState();
    if (widget.showAll == true) {
      _dropDownHeaderItemStrings = '全部';
      _brandSortConditions = [
        SortCondition(name: '全部', isSelected: true, value: '')
      ];
    } else {
      if (widget.options.isNotEmpty) {
        int defaultSelected = widget.defaultSelectionIdx ?? 0;
        _dropDownHeaderItemStrings = widget.options[defaultSelected]['name'];
      }
    }
    if (widget.options.isNotEmpty) {
      widget.options.forEach((item) {
        int defaultSelected = widget.defaultSelectionIdx ?? 0; //默认选中
        bool isSelected = false;
        if (widget.showAll == false) {
          //不显示全部
          isSelected = widget.options[defaultSelected]['id'] == item['id'];
        }
        _brandSortConditions.add(SortCondition(
            name: item['name'], isSelected: isSelected, value: item['id']));
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (_brandSortConditions.isEmpty) {
      return const Padding(padding: EdgeInsets.all(5.0));
    }
    return Stack(key: widget.stackKey, children: [
      Column(
        children: [
          GZXDropDownHeader(
            items: [
              GZXDropDownHeaderItem(_dropDownHeaderItemStrings),
            ],
            stackKey: widget.stackKey,
            controller: _dropdownMenuController,
          ),
          widget.content
        ],
      ),
      GZXDropDownMenu(
        animationMilliseconds: 50,
        controller: _dropdownMenuController,
        menus: [
          GZXDropdownMenuBuilder(
              dropDownHeight: 40 * _brandSortConditions.length.toDouble(),
              dropDownWidget:
                  _buildConditionListWidget(_brandSortConditions, (value) {
                _selectBrandSortCondition = value;

                setState(() {
                  dynamic name = _selectBrandSortCondition.name;
                  _selectBrandSortCondition = value;
                  _dropDownHeaderItemStrings = _selectBrandSortCondition.name;
                });
                _dropdownMenuController.hide();

                widget.itemTap!(value);
              })),
        ],
      )
    ]);
  }

//筛选
  _buildConditionListWidget(items, void itemOnTap(SortCondition)) {
    return ListView.separated(
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemCount: items.length,
      // item 的个数
      separatorBuilder: (BuildContext context, int index) =>
          const Divider(height: 1.0),
      // 添加分割线
      itemBuilder: (BuildContext context, int index) {
        dynamic sortCondition = items[index];
        return GestureDetector(
          onTap: () {
            for (var value in items) {
              value.isSelected = false;
            }
            sortCondition.isSelected = true;
            itemOnTap(sortCondition);
          },
          child: Container(
            height: 40,
            child: Row(
              children: <Widget>[
                const SizedBox(
                  width: 16,
                ),
                Expanded(
                  child: Text(
                    sortCondition.name,
                    style: TextStyle(
                      color:
                          sortCondition.isSelected ? Colors.red : Colors.black,
                    ),
                  ),
                ),
                sortCondition.isSelected
                    ? Icon(
                        Icons.check,
                        color: Theme.of(context).primaryColor,
                        size: 16,
                      )
                    : const SizedBox(),
                const SizedBox(
                  width: 16,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}
